//
//  SEGMarketListm
//  Commom
//
//  Created by 梁学彰 on 2020/6/9.
//

#import "SEGMarketListViewModel.h"


@implementation SEGMarketListViewModel
#pragma mark - life cycle
- (instancetype)init {
    if (self = [super init]) {
        [self initData];
    }
    return self;
}

#pragma mark - init
- (void)initData {
    self.page = 1;
    self.positionType = SEGAdvlistType_SECONDHAND;
}

#pragma mark - send request
- (RACSignal *)loadMarketTypeList {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        [self.socialManager requestMarketTypeList:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            NSMutableArray *tempArr = [NSMutableArray array];
            if (isSuccessed) {
                if (self.socialManager.marketTypeList.count != 0) {//展示整栏
                    //初始化选择标签视图
                    //在最前面拼接全部标签
                    SEGNewMarketTypeModel *model = [[SEGNewMarketTypeModel alloc] init];
                    model.marketId = @"";
                    model.marketName = @"全部";
                    [self.socialManager.marketTypeList insertObject:model atIndex:0];
                    [self.socialManager.marketTypeList enumerateObjectsUsingBlock:^(SEGNewMarketTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [tempArr addObject:obj.marketName];
                    }];
                }
                [subscriber sendNext:tempArr];
            }else {
                [subscriber sendError:nil];
            }
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)seg_requestMarketList {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        NSString *scopeType = [[NSUserDefaults standardUserDefaults] valueForKey:kMarketScopeType];
        [self.socialManager requestMarketListByTypeID:self.marketType scopeId:scopeType pageNo:[NSString stringWithFormat:@"%ld",(long)self.page] Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                // 成功，修改右上角按钮文字
                [subscriber sendNext:nil];
            } else {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)loadAdvlist {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        [[SEGAdvlistManager sharedManager] segRequestAdvlistWithPositionType:self.positionType completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
            if (isSuccessed) {
                [subscriber sendNext:result];
            }else {
                [subscriber sendError:nil];
            }
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}

- (void)loadPublishMarketType {
    [self.socialManager requestFindDictionaryInfoByCode:@"market_type" Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
    }];
}

- (RACSignal *)shareVCActionButtonPressedWithType:(SEGShareVCActionType)actionType {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        SEGQueryGoodsIdelModel *model = self.socialManager.marketList[self.selectedIndexPath.section];
        NSString* objType = [model convertToObjType];
        
        switch (actionType) {
            case SEGShareVCActionType_Again:
            {
                //重新上架
                [subscriber sendNext:[NSNumber numberWithInteger:actionType]];
                [subscriber sendCompleted];
                break;
            }
            case SEGShareVCActionType_SellOut:
            {
                //已出手
                [self.sHManager requestUpdateStatusBygoodsId:model.goodsId
                                                     objType:[model convertToObjType]
                                                      status:[NSString stringWithFormat:@"%lu",(unsigned long)SEGEnumIdleStatus_SaleOut]
                                                    Finished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage) {
                    if (isSuccessed) {
                        [subscriber sendNext:[NSNumber numberWithInteger:actionType]];
                    }
                    //成功失败都是弹出提示
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                    
                }];
                break;
            }
            case SEGShareVCActionType_Edit:
            {
                //编辑
                [subscriber sendNext:[NSNumber numberWithInteger:actionType]];
                [subscriber sendCompleted];
                break;
            }
            case SEGShareVCActionType_Delete:
            {
                [self.sHManager requestUpdateStatusBygoodsId:model.goodsId
                                                     objType:[model convertToObjType]
                                                      status:[NSString stringWithFormat:@"%lu",(unsigned long)SEGEnumIdleStatus_Remove]
                                                    Finished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage) {
                    
                    if (isSuccessed) {
                        [subscriber sendNext:[NSNumber numberWithInteger:actionType]];
                    }
                    //成功失败都是弹出提示
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }];
                break;
            }
            case SEGShareVCActionType_Report://举报
            {
                [subscriber sendNext:[NSNumber numberWithInteger:actionType]];
                [subscriber sendCompleted];
                break;
            }
            case SEGShareVCActionType_NotIntersting:
            {
                NSMutableDictionary *notLikeDict;
                NSDictionary *tempDict = [[NSUserDefaults standardUserDefaults] objectForKey:kNeighborhoodNotLikeArray];
                if (tempDict && [tempDict isKindOfClass:[NSDictionary class]]) {
                    notLikeDict = [NSMutableDictionary dictionaryWithDictionary:tempDict];
                }else {
                    notLikeDict = [NSMutableDictionary dictionary];
                }
                
                NSMutableArray *array;
                NSArray *tempArr = [tempDict objectForKey:kAccountUserID];
                if (tempArr && [tempArr isKindOfClass:[NSArray class]]) {
                    array = [NSMutableArray arrayWithArray:tempArr];
                }else {
                    array = [NSMutableArray array];
                }
                //本地记录不感兴趣的数据
                NSDictionary *dic = @{@"objType":ValueToString(objType), @"objId":ValueToString(model.goodsId)};
                [array addObject:dic];
                [notLikeDict setObject:array forKey:kAccountUserID];
                [[NSUserDefaults standardUserDefaults] setObject:notLikeDict forKey:kNeighborhoodNotLikeArray];
                [[NSUserDefaults standardUserDefaults] synchronize];
                //本地删除
                [self.socialManager.marketList removeObjectAtIndex:self.selectedIndexPath.section];
                [subscriber sendNext:[NSNumber numberWithInteger:actionType]];
                [subscriber sendCompleted];
            }
            default:
                [subscriber sendCompleted];
                break;
        }
        
        return nil;
    }];
    return signal;
}

//接口
- (RACSignal *)loadHLBMarketTypeList {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [subscriber sendNext:@"1"];
        __weak typeof (self) weakSelf = self;
        [self.socialManager requestMarketTypeList:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [subscriber sendNext:@"0"];
            if (isSuccessed) {
                if (weakSelf.socialManager.marketTypeList.count == 0) {//不展示整栏
                    [subscriber sendNext:@[]];
                }else {
                    //初始化选择标签视图
                    //在最前面拼接全部标签
                    SEGNewMarketTypeModel *model = [[SEGNewMarketTypeModel alloc] init];
                    model.marketId = @"";
                    model.marketName = @"全部";
                    [weakSelf.socialManager.marketTypeList insertObject:model atIndex:0];
                    
                    NSMutableArray *tempArr = [NSMutableArray array];
                    [weakSelf.socialManager.marketTypeList enumerateObjectsUsingBlock:^(SEGNewMarketTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [tempArr addObject:obj.marketName];
                    }];
                    [subscriber sendNext:tempArr];
                    
                    SEGNewMarketTypeModel *model2 = weakSelf.socialManager.marketTypeList[weakSelf.marketIndex];
                    weakSelf.marketType = model2.marketId;
                }
            }else {
                [subscriber sendError:nil];
            }
            [subscriber sendCompleted];
        }];
        
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)seg_requestHLBMarketList {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        __weak typeof(self) weakSelf = self;
        [subscriber sendNext:@"1"];
        [self.socialManager requestMarketListByTypeID:self.marketType scopeId:ValueToString(self.scopeType) pageNo:[NSString stringWithFormat:@"%ld",(long)self.page] Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [subscriber sendNext:@"0"];
            if (isSuccessed) {
                [subscriber sendCompleted];
            }else {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
        }];
        
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)requesPublishScopeList {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        WeakSelf;
        [self.socialManager requesPublishScopeListFinished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage) {
            if (!isSuccessed) {
                [subscriber sendError:nil];
                return;
            }
            [weakSelf.socialManager.publishScopeList enumerateObjectsUsingBlock:^(PublishScopeListModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
                if (model.scopeType.integerValue == SEGEnumScopeList_All) { // 默认全部
                    // 设置导航右边文字
                    [subscriber sendNext:model.scopeDesc];
//                    
                    *stop = YES;
                }
            }];
            [subscriber sendCompleted];
        }];
        
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)hlb_cellPraiseButtonActionWithIndexPath:(NSIndexPath *)indexPath {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        if (!self.socialManager.marketList || self.socialManager.marketList.count <= indexPath.section) {
            [subscriber sendError:nil];
            return nil;
        }
        
        SEGQueryGoodsIdelModel *model = self.socialManager.marketList[indexPath.section];
        NSString* objType = [SEGBasicBussinessEnums getSEGEnumIdelExchange:SEGEnumIdelExchange_SecondHand];
        
        // 防止重复点赞
        WeakSelf;
        if (self.isLiking) {
            [subscriber sendError:nil];
            return nil;
        }
        self.isLiking = YES;
        if ([[model.isLike stringValue] isEqualToString:@"1"]) {
            //这里取消点赞行为方法
            [self.socialManager requestCancelPraiseByobjId:model.goodsId
                                                   objType:objType
                                                  Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    model.isLike = @(0);
                    model.attenCount = @([model.attenCount intValue] - 1);
                    // [self.tableView reloadData];
                    [subscriber sendNext:nil];
                }else {
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
                weakSelf.isLiking = NO;
                [subscriber sendCompleted];
            }];
        } else {
            //这里执行点赞行为方法
            [self.socialManager requestPraiseAttentByObjId:model.goodsId
                                                   ObjType:objType
                                           objPicUrlForMsg:model.img1
                                            objTitleForMsg:model.title
                                            byReviewUserId:model.userId
                                               parentObjId:model.goodsId
                                             parentObjType:objType
                                             operationType:[NSString stringWithFormat:@"%ld", (unsigned long)SEGNeighbourhoodOperationType_Market]
                                                  isParent:@"1"
                                                  Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    model.isLike = @(1);
                    model.attenCount = @([model.attenCount intValue] + 1);
                    [subscriber sendNext:nil];
                } else {
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
                weakSelf.isLiking = NO;
                [subscriber sendCompleted];
            }];
        }
        
        
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)refreshListViewWithIndex:(NSIndexPath *)indexPath objId:(NSString *)objId objType:(NSString *)objType isDelete:(BOOL)isDelete {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        // 刷新单条集市数据
        [self.sHManager requestQueryMarketSingleWithGoodsId:objId objType:objType finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            if (!isSuccessed) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                return;
            }
            [subscriber sendCompleted];
        }];
        
        
        return nil;
    }];
    return signal;
}

#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response
- (NSDictionary *)getCellMoreButtonActionParamsWithIndexPath:(NSIndexPath *)indexPath {
    self.selectedIndexPath = indexPath;
    SEGQueryGoodsIdelModel *model = self.socialManager.marketList[self.selectedIndexPath.section];
    SEGEnumIdelExchange IdelExchange = [model.type integerValue];
    NSString* objType = [SEGBasicBussinessEnums getSEGEnumIdelExchange:IdelExchange];
    BOOL isMy = [ValueToString(model.userId) isEqualToString:kAccountUserID] ? YES : NO;
    
    NSString *shareContent;
    NSString *shareImageUrl;
    
    
    
    NSArray *otherActionTypesArr;
    //集市
    shareContent = [NSString stringWithFormat:@"%@，%@", model.title, model.exp];
    NSArray *picArray = [model.img1 componentsSeparatedByString:@","];
    NSMutableArray *array = [NSMutableArray array];
    [picArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.length > 0) {
            [array addObject:obj];
        }
    }];
    if (picArray.count > 0) {
        shareImageUrl = picArray[0];
    }
    
    if (isMy) {
        switch ([model.status integerValue]) {
            case SEGEnumIdleStatus_Idle:
            {
                otherActionTypesArr = @[@(SEGShareVCActionType_Edit), @(SEGShareVCActionType_SellOut), @(SEGShareVCActionType_Delete)];
                break;
            }
            case SEGEnumIdleStatus_SaleOut:
            {
                otherActionTypesArr = @[@(SEGShareVCActionType_Again), @(SEGShareVCActionType_Delete)];
                break;
            }
            case SEGEnumIdleStatus_Remove:{
            }
                break;
        }
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@(SEGShareVCType_Market) forKey:@"shareVCType"];
    [params setValue:[SEGBasicBussinessEnums getSectionWithObjType:objType] forKey:@"objSection"];
    [params setValue:model.goodsId forKey:@"objID"];
    [params setValue:shareContent forKey:@"sharecontent"];
    
    
    NSString *shareTitle = [NSString stringWithFormat:@"“%@”发布了一条动态信息",model.userName];
    NSString* shareUrlString = [NSString stringWithFormat:@"%@%@?#/ugc?objId=%@&objType=%@&operationType=%@&app_platform_code=%@&company_platform_code=%@&scheme=%@", kClientRootURL, kNewShareURLPre, model.goodsId, objType, [NSString stringWithFormat:@"%lu",(unsigned long)SEGNeighbourhoodOperationType_Market], kAppPlatformCode, kAppPlatformCode, kOpenAppScheme];
    [params setValue:shareUrlString forKey:@"inviteurl"];
    [params setValue:shareTitle forKey:@"sharetitle"];
    
    if (shareImageUrl && shareImageUrl.length > 0) {
        NSString *imageUrl = [NSString stringWithFormat:@"%@%@",kClientSmallImageRootURL,shareImageUrl];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]];
        [params setValue:image forKey:@"shareImage"];
    }
    
    //添加举报按钮
    if (!isMy) {
        NSMutableArray *temp = [NSMutableArray arrayWithArray:otherActionTypesArr];
        // [需求 8043] 集市去掉不感兴趣
        // [temp addObject:@(SEGShareVCActionType_NotIntersting)];
        [temp addObject:@(SEGShareVCActionType_Report)];
        [params setValue:temp forKey:@"otherActionTypesArr"];
    }else {
        [params setValue:otherActionTypesArr forKey:@"otherActionTypesArr"];
    }
    
    return params;
}
#pragma mark - private methods

#pragma mark - setter and getter
- (SEGCommunitySocialManager *)socialManager {
    
    if (!_socialManager) {
        _socialManager = [[SEGCommunitySocialManager alloc] init];
    }
    return _socialManager;
}

- (SEGSHManager *)sHManager {
    if (!_sHManager) {
        _sHManager = [[SEGSHManager alloc] init];
    }
    return _sHManager;
}

- (NSString *)marketType {
    if (!_marketType) {
        _marketType = @"";
    }
    return _marketType;
}

@end
